
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoDatabase;

public class MongoConnClient 
{

	
	private MongoClient mongoClient;
	private String strMongoClientURI;
	private String strDefaultDB;
	
	public void setMongoClientURI(String strMongoClientURI)
	{
		this.strMongoClientURI = strMongoClientURI;
		String strMongoClientURITmp=strMongoClientURI.replace("mongodb://", "");
		int nDBStartPos = strMongoClientURITmp.indexOf("/");
		int nDBEndPos = strMongoClientURITmp.indexOf("?");
		strDefaultDB =strMongoClientURITmp.substring(nDBStartPos+1, nDBEndPos);
	}
	
	public MongoClient getMongoClient()
	{
		return this.mongoClient;
	}
	
	public MongoDatabase getDefaultDB()
	{
		return this.mongoClient.getDatabase(strDefaultDB);
	}
	
	public MongoDatabase getDatabaseDB(String strDBName)
	{
		return this.mongoClient.getDatabase(strDBName);
	}
	
	public boolean connect()
	{
		try 
		{
			//mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
			//mongodb://user1:pwd@127.0.0.1/test?authMechanism=MONGODB-CR&maxPoolSize=500
			//参考文档:http://www.runoob.com/mongodb/mongodb-connections.html
			//参考文档:http://api.mongodb.com/java/3.0/com/mongodb/MongoClientURI.html    http://api.mongodb.com/java/3.0/com/mongodb/MongoClientOptions.html
			//参考文档:https://docs.mongodb.com/manual/reference/connection-string/ https://docs.mongodb.com/manual/reference/connection-string/
			//参考文档:https://yq.aliyun.com/articles/8461?spm=0.0.0.0.k3SIwV
			//解决办法：
			//对@使用16进制进行URL编码：%40
			//对：使用16进制进行URL编码：%3A
			//用上面16进制的URL编码代替原本的字符就行了。
			//   : /  @ , ?  &  ' "   这八个字符尽量不用，避免转义
			
			MongoClientURI mongoClientURI = new MongoClientURI(strMongoClientURI.trim());
			this.mongoClient = new MongoClient(mongoClientURI);
			
		} catch (Exception e) {
			//log.error("connect mongodb failed,"+"uri:,"+this.strMongoClientURI+","+e.getMessage(), e);
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	
	public void close()
	{
		if(this.mongoClient != null)
		{
			this.mongoClient.close();
		}
	}
	
}
